package com.ff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ff.common.CustemException;
import com.ff.dto.SetmealDto;
import com.ff.entity.Setmeal;
import com.ff.entity.SetmealDish;
import com.ff.mapper.SetmealMapper;
import com.ff.service.SetmealDishService;
import com.ff.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        for (SetmealDish tmp:list){
            tmp.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(list);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可用删除
        QueryWrapper<Setmeal> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",ids);
        queryWrapper.eq("status",1);
        int count = this.count(queryWrapper);
        //如果不能删除，抛出一个业务异常
        if (count>0){
            throw new CustemException("有套餐正在售卖中,不能删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);
        //删除关系表中的数据----setmeal_dish
        QueryWrapper<SetmealDish> wrapper=new QueryWrapper<>();
        wrapper.in("setmeal_id",ids);
        setmealDishService.remove(wrapper);
    }
}
